package com.csdj.common;
import com.csdj.utils.MessageLangUtil;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
 * WebResult结果转换
 */
public class WebResult {
    private Logger log = Logger.getLogger("WebResult");
    private int code;
    private String msg;
    private Map<String,Object> result = new HashMap<>();

    public WebResult(int code) {
        log.info("WebResult(int code)");
        this.code = code;
        //获取当前线程的请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String langHeader = request.getHeader("Accept-Language");
        if(StringUtils.hasText(langHeader)){
            String lang = langHeader.split(",")[0];
            this.msg = MessageLangUtil.getMsg(code,lang);
        }else{
            this.msg = MessageLangUtil.getMsg(code, "zh");
        }
    }

    public WebResult(){}

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getResult() {
        return result;
    }

    public void setResult(Map<String, Object> result) {
        this.result = result;
    }

    public WebResult putData(String key,Object data){
        this.result.put(key,data);
        return this;
    }
}
